require.config({baseUrl: '/js/lib',urlArgs: "v0.0.3"});
require(['zepto', 'lib'], function($, lib) {
  var fn = {}, lib = new lib();
  $.extend(fn, {
    goodsTotalNum: 0,
    orderType: (lib.getUrlParam('ot') ? lib.getUrlParam('ot') : '1'),
    orderTypeList: {'1': '待支付', '2': '待提货', '3': '已完成', '4': '已取消'},
    init: function(){
      var _t = this;
      _t.initPage();
      _t.bindEvent();
    },
    bindEvent: function(){
      var _t = this;
      /*删除/取消订单*/
      $(document).on("tap", ".ui-del-order, .ui-cancel-order", function(){
        lib.onLoading();
        var _this = this, url = 'order/deleteOrder.action', orderId = $(this).parents('.ui-order-operation').attr('data-orderId'), orderType = 1;
        if($(this).attr('class') === 'ui-cancel-order'){
          url = 'order/cancelOrder.action';
        }
        if($(_this).parents('.ui-order-operation').attr('data-orderSonId') !== 'undefined'){
          orderId = $(_this).parents('.ui-order-operation').attr('data-orderSonId')
          orderType = 2
        }
        lib.ajx(lib.getReq().ser + url, {orderId: orderId, orderType: orderType}, function(data){
          if(data.infocode === "0") $(_this).parents('.ui-order-operation').remove();
          else lib.showMessage(data.info);
        }, function(){
          lib.showMessage('网络延迟，请稍后再试');
        });
      });
      
      /*再次购买*/
      $(document).on("tap", ".ui-buy-again", function(){
        lib.onLoading();
        var _this = this, url = 'order/makeOrder.action', orderId = $(_this).parent().attr('data-orderId'), orderType = 1;
        if($(_this).parent().attr('data-orderSonId') !== 'undefined'){
          orderId = $(_this).parent().attr('data-orderSonId')
          orderType = 2
        }
        location.href = `/order/confirm_order.html?oId=${orderId}&ot=${orderType}&mt=3`;
      });
      
      $(document).on("tap", ".ui-tuikuan", function(){
        $("#ui-tishi-k").remove();
        $('body').append(`
          <div id="ui-tishi-k" style="position: fixed;width:100%; height: 100%; top: 0;background-color: rgba(0,0,0,0.5)">
            <ul style="top: 50%;left: 50%;position: absolute;-webkit-transform: translate(-50%,-50%);transform: translate(-50%,-50%);width: 11.6rem;border-radius: 0.4rem;background-color: #ffffff;">
              <li style="padding-top: 0.8rem;text-align:center;font-size: 0.68rem; font-weight: 500; line-height: 1.56; letter-spacing: 2.7px; color: #333333;">申请退款</li>
              <li style="padding: 0 0.6rem;letter-spacing: 2.2px;">
                <p style="color: #999;font-size: 0.56rem;line-height: 3">退款时间:<span style="color: #333">${new Date().getFullYear() + '-' + (new Date().getMonth() + 1) + '-' + new Date().getDate() + '  ' + new Date().getHours() + ':' + new Date().getMinutes()}</span></p>
                <p style="color: #999;font-size: 0.56rem;line-height: 3">退款金额:<span style="color: #333">${$(this).attr('data-orderSonPayline')}</span></p>
              </li>
              <li style="border-top: 1px solid #ddd;font-size: 0.68rem;text-align:center;line-height: 1.8rem;margin-top: 0.6rem">
                <div class="ui-tuikuan-cancel" style="width:50%;float:left;color: #666">取消</div>
                <div class="ui-tuikuan-confirm" style="overflow: hidden;color: #308eed;border-left: 1px solid #ddd;">确定</div>
              </li>
            </ul>
          </div>
        `);
      });
      
      $(document).on("tap", ".ui-tuikuan-cancel", function(){
        $("#ui-tishi-k").remove();
      });
      
      $(document).on("tap", ".ui-tuikuan-confirm", function(){
        var orderId = $('.ui-tuikuan').parent().attr('data-orderSonId')
        lib.ajx(lib.getReq().ser + 'order/cancelOrder.action', {orderId: orderId, orderType: 2}, function(data){
          if(data.infocode === "0") {
            lib.showMessage("退款提交成功  退款金额将在<br> 72小时内返还退款账户")
            $(".ui-tuikuan").remove()
            $("#ui-tishi-k").remove();
            setTimeout(function(){
              history.back()
            }, 1000)
          }
          else lib.showMessage(data.info);
        }, function(){
          lib.showMessage('网络延迟，请稍后再试');
        });
      });
      
      /*去支付*/
      $(document).on("tap", ".ui-go-pay", function(){
        lib.onLoading();
        if(window.browser.versions.weixin){
          if(lib.getIsOnline()){
            location.href = 'https://open.weixin.qq.com/connect/oauth2/authorize?appid=' + lib.getReq().appid + 
            '&redirect_uri=http://api.chengshijiugui.com/csjgmanager/pay/wxPay.action&response_type=code&scope=snsapi_base&state='+ $(this).parents('.ui-order-operation').attr('data-orderId') + '#wechat_redirect';
            return;
          }else{
            location.href = 'https://open.weixin.qq.com/connect/oauth2/authorize?appid=' + lib.getReq().appid + 
            '&redirect_uri=http://api.chengshijiugui.com/csjgmanager/pay/wxPay.action&response_type=code&scope=snsapi_base&state='+ $(this).parents('.ui-order-operation').attr('data-orderId')  + '#wechat_redirect';
          }
        }else{
          lib.ajx(lib.getReq().ser + '/pay/alipay.action', {orderId: $(this).parents('.ui-order-operation').attr('data-orderId'), originType: 1}, function(data){
            if(data.infocode === "0"){
              location.href = data.info;
            }else{
              lib.showMessage(data.info);
            }
          }, function(){
            lib.showMessage('网络错误,请稍后再试');
          });
        }
      });
    },
    initPage: function(){
      var _t = this;
      lib.ajx(lib.getReq().ser + '/order/orderDetail.action', {orderStatus: _t.orderType, orderType: (_t.orderType === '2' || _t.orderType === '3' ? 2 : 1), orderId: lib.getUrlParam('oId')}, function(data){
        if(data.infocode === "0"){
          var lastTime = (24 * 60 * 60 * 1000) - (new Date() - new Date(data.info.createDate));
          sessionStorage.invoiceInfo = JSON.stringify(data.info);
          function countDown(){
            setTimeout(function(){
              var lastTime = (24 * 60 * 60 * 1000) - (new Date() - new Date(data.info.createDate));
              $('.ui-zhifu-lastTime').text(lastTime > 0 ? parseInt(lastTime / 1000 / 3600)+'小时'+ parseInt(lastTime % (1000 * 3600) / (1000 * 60)) +'分钟' : '支付超时');
              if(lastTime > 0){
                countDown();
              }
            }, 30000)
          }
          countDown();
          var h = '';
          h += `<div>`
          if(_t.orderType === '1')        
            h += `<div class="ui-zhifu-time">
                    <i></i>
                    <span>订单剩余支付时间：<i class="ui-zhifu-lastTime">${lastTime > 0 ? parseInt(lastTime / 1000 / 3600)+'小时'+ parseInt(lastTime % (1000 * 3600) / (1000 * 60)) +'分钟' : '支付超时'}</i></span>
                  </div>  `;
                  
            h += `<ul class="ui-order-info">
                <li>
                  <i>订单编号：</i>
                  <i>${data.info.storage[0].orderSonId ? data.info.storage[0].orderSonId: data.info.orderId}</i>
                  <i style="float:right;${_t.orderType === '1' ? 'color: #f01e1e': 'color: #999'}">${_t.orderTypeList[_t.orderType]}</i>
                </li>
                <li>
                  <i>下单时间：</i>
                  <i>${data.info.createDate}</i>
                </li>
              </ul>
            </div>`
            $.each(data.info.storage, function(K, V) {
              h +=`<ul class="ui-order-info ui-mar-b-20">
                    <li>
                      <i>取货地址：</i>
                      <i>${V.address}</i>
                    </li>
                    <li>
                      <i>营业时间：</i>
                      <i>${V.startTime}-${V.endTime}</i>
                    </li>
                    <li style="${V.verifyCode ? '' : 'display:none'}">
                      <i>提货密码：</i>
                      <i>${V.verifyCode}</i>
                    </li>
                    <li>
                      <i>领取方法：</i>
                      <i>向商家出示提货密码即可领酒</i>
                    </li>
                  </ul>
                  <div class="ui-goods-info ui-mar-b-20">
                    <div class="ui-shop-name"><i>${V.storageName}</i><i class="ui-r-b" style="margin-top: 0.62rem;margin-left: 5px"></i></div>
                    <div class="ui-g-detail">
                      <ul>`
              $.each(V.goodsList, function(k, v){
                _t.goodsTotalNum += v.goodsNum;
                h += `<li>
                        <div class="ui-g-img"><img src="${lib.getReq().imgPath + v.mainPictureJpg}" /></div>
                        <ul class="ui-g-desc">
                          <li>${v.chName}</li>
                          <li>
                            <i class="ui-g-price">￥${v.sellPrice}</i>
                            <i class="ui-g-num">x${v.goodsNum}</i>
                          </li>
                        </ul>
                      </li>`;
              
              })
              
              h += "</ul></div></div>";
            	
            });
            h +=`<ul class="ui-order-other ui-mar-b-20">
                  <li>
                    <a href="#">
                      <i>支付方式</i>
                      ${ data.info.payTypeId == '18' ? '<i class="ui-weixin-icon" style="margin-top: 0.52rem;float: right;"></i><i style="float:right;margin-right: 0.1rem">微信支付</i>':
                      '<i class="ui-zhifubao-icon" style="margin-top: 0.58rem;float: right;"></i><i style="float:right;margin-right: 0.1rem">支付宝</i>'}
                    </a>
                  </li>
                  <li>
                    <a href="/invoice.html?oId=${lib.getUrlParam('oId')}&backUrl=${lib.getBackUrl()}">
                      <i>发票信息</i>
                      <i style="float:right;margin-right: 0.6rem">${data.info.invoiceType === '2' ? '个人发票' : (data.info.invoiceType === '1' ? '单位发票' : '不开发票')}</i>
                    </a>
                  </li>
                </ul>
                
                <ul class="ui-order-i ui-mar-b-20">
                  <li>
                      <i>商品金额：</i>
                      <i>共${_t.goodsTotalNum}件商品   共计￥${data.info.orderMoney}</i>
                    </a>
                  </li>
                  <li class="ui-border-bottom">
                      <i>运费金额：</i>
                      <i>￥0</i>
                    </a>
                  </li>
                  <li>
                      <i>总计金额：</i>
                      <i>￥${data.info.orderMoney}</i>
                    </a>
                  </li>
                </ul>
                <div style="clear: both;"></div>
                <!--订单金额end-->`;
          if(_t.orderType === '1')  
            h += `<ul class="ui-order-operation" data-orderId="${data.info.orderId}" data-orderSonId="${data.info.storage[0].orderSonId}">
                    <li class="ui-cancel-order">取消订单</li>
                    <li class="ui-go-pay">去支付</li>
                  </ul>`;
          else 
            h += `<div style="position: fixed;bottom: 0;width: 100%;box-shadow: 0 0 10px #666" data-orderId="${data.info.orderId}" data-orderSonId="${data.info.storage[0].orderSonId}">
                    <botton class="ui-red-botton ui-tuikuan" data-orderSonPayline="${data.info.payOnline}" style='float:left;width:34%;color: #666;background-color: white;${_t.orderType === '2' ? 'display:block' : 'display:none' }'>申请退款</botton>
                    <botton class="ui-red-botton ui-buy-again" style="overflow:hidden;width: auto;">再次购买</botton>
                  </div>`;
          $('body').append(h);
        }else if(data.infocode === "2"){
          location.href = "/login.html?backUrl=" + lib.getBackUrl();
        }else{
          lib.showMessage(data.info);
        }
      }, function(){
        lib.showMessage('网络延时，请稍后再试');
      });
    }
  });
  
  fn.init();
});